<template>
  <el-dialog class="dialogClass" :model-value="dialogVisible" title="改卡有效期" width="80%" :before-close="handleClose">
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="人员列表"
        rowKey="empid"
        :columns="columns"
        :request-api="getTableList"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4 }"
        :data-callback="dataCallback"
        v-loading="loading"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button-group>
            <el-button type="primary" text :icon="Edit" @click="_batchEditValidity(scope.selectedListIds)">修改当前</el-button>
            <el-button type="primary" text :icon="Edit" @click="_editValidity">修改全部</el-button>
          </el-button-group>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
      </ProTable>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="CardValidityDialog">
import { ref, h } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ElDatePicker, ElMessage, ElMessageBox } from "element-plus";
import { Edit } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { getValidEmployeeList, updateValid, updateValidAll } from "@/api/modules/cardIssuingCenter/employeeManage";
const props = defineProps<{ orgUnitIDs: string[]; dialogVisible: boolean; handleClose: () => void }>();

const proTable = ref();
const validityDate = ref();
const loading = ref(false);

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records || [],
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getValidEmployeeList({ ...newParams, orgUnitIDs: props.orgUnitIDs });
};

const columns = [
  { type: "selection", fixed: "left", width: 60 },

  {
    prop: "clause",
    label: "姓名",
    isShow: false,
    search: { el: "input" },
    minWidth: 120
  },
  {
    prop: "validDays",
    label: "有效期",
    isShow: false,
    search: { el: "input-number", defaultValue: 30, props: { controlsPosition: "right", min: "1" } }
  },
  {
    prop: "empcode",
    label: "编号",
    minWidth: 200
  },
  {
    prop: "empname",
    label: "姓名",
    minWidth: 120
  },

  {
    prop: "cardType",
    label: "部门",
    minWidth: 200
  },
  {
    prop: "cardvalid",
    label: "卡有效期",
    minWidth: 200
  },
  {
    prop: "rulevalid",
    label: "门禁有效期",
    minWidth: 200
  },

  {
    prop: "bcard",
    label: "发卡",
    minWidth: 120,
    render: scope => {
      return <el-checkbox disabled checked={scope.row.bcard}></el-checkbox>;
    }
  },
  {
    prop: "bfinger",
    label: "指纹",
    minWidth: 120,
    render: scope => {
      return <el-checkbox disabled checked={scope.row.bfinger}></el-checkbox>;
    }
  },
  {
    prop: "block",
    label: "挂失",
    minWidth: 120,
    render: scope => {
      return <el-checkbox disabled checked={scope.row.block}></el-checkbox>;
    }
  }
];

/**
 * 批量修改有效期
 */
const _batchEditValidity = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要修改有效期的人员");
    return false;
  }

  validityDate.value = dayjs(new Date(dayjs(new Date()).format("YYYY-MM-DD") + " 23:59:59")).format("YYYY-MM-DD HH:mm:ss");

  ElMessageBox({
    title: "系统提示",
    message: () =>
      h("div", null, [
        h("span", { style: { marginRight: "10px" } }, "修改有效期至："),
        h(ElDatePicker, {
          modelValue: validityDate.value,
          type: "datetime",
          "onUpdate:modelValue": val => {
            validityDate.value = dayjs(new Date(dayjs(val).format("YYYY-MM-DD") + " 23:59:59")).format("YYYY-MM-DD HH:mm:ss");
          }
        })
      ]),
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    beforeClose: async (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          await updateValid({ dateParam1: validityDate.value, list: selectedListIds });
          ElMessage.success("更新有效期成功");
          proTable.value.clearSelection();
          proTable.value.getTableList();
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

/**
 * 修改所有有效期
 */
const _editValidity = async () => {
  validityDate.value = dayjs(new Date(dayjs(new Date()).format("YYYY-MM-DD") + " 23:59:59")).format("YYYY-MM-DD HH:mm:ss");
  ElMessageBox({
    title: "系统提示",
    message: () =>
      h("div", null, [
        h("span", { style: { marginRight: "10px" } }, "修改有效期至："),
        h(ElDatePicker, {
          modelValue: validityDate.value,
          type: "datetime",
          "onUpdate:modelValue": (val: boolean | string | number) => {
            validityDate.value = val;
          }
        })
      ]),
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    beforeClose: async (action, instance, done) => {
      beforeCloseFunc(action, instance, done, async () => {
        try {
          await updateValidAll({ dateParam1: validityDate.value, orgUnitIDs: props.orgUnitIDs });
          ElMessage.success("更新有效期成功");
          instance.confirmButtonLoading = false;
          done();
        } catch (error) {
          instance.confirmButtonLoading = false;
          console.log(error);
        }
      });
    }
  });
};

/**
 * 消息框关闭
 */
const beforeCloseFunc = async (action, instance, done, cb) => {
  if (action === "confirm") {
    instance.confirmButtonLoading = true;
    cb && cb();
  } else {
    done();
  }
};
</script>
<style scoped lang="scss">
.table-box {
  width: 100%;
  height: 80vh;
}
</style>
